﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

using System.IdentityModel.Tokens.Jwt;

using System.Security.Claims;

using System.Text;

namespace Jwt.Server.Controllers;

[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class TokenController : ControllerBase
{
    const string algorithm = "HS256";
    private readonly JwtConfig _jwtConfig;
    public TokenController(JwtConfig jwtConfig)
    {
        _jwtConfig = jwtConfig;
    }
    [HttpGet]
    public string Get(string userId = "test", string password = "123")
    {
        //各种验证
        if ((userId != "test" && userId != "admin") || password != "123")
            return "";

        List<Claim> claims = [
            new Claim(ClaimTypes.Name, userId),
            new Claim(ClaimTypes.GivenName,"上帝")
            ];
        if (userId == "admin")
            claims.Add(new Claim(ClaimTypes.Role, "Admin"));

        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.SecretKey));
        SigningCredentials signingCredentials = new SigningCredentials(key, algorithm);
        JwtSecurityToken token = new JwtSecurityToken(_jwtConfig.Issuer, _jwtConfig.Audience, claims, DateTime.Now, DateTime.Now.AddDays(1), signingCredentials);
        return new JwtSecurityTokenHandler().WriteToken(token);

    }
}
